/*
 * @Author: NtyAaron
 * @Date: 2021-04-12 11:13:45
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-07-06 13:43:23
 * @Description: 活动及培训
 * @FilePath: \dwq\pages\train\train.js
 */
const app = getApp()
import { getCityList, getAllIndustry, getCategoryList, getChildList, getArticlePage } from '../../api/article/article'
import { saveCollect, delCollect } from '../../api/article/article'
import { getPosterList } from '../../api/advert/advert'
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog'
import { _t } from '../../i18n/base'

Page({
  data: {
    // 文章分类
    categoryList: [],
    // 行业列表
    industryList: [],
    // 城市列表
    cityList: [],
    // 文章列表
    momentList: [],
    industry: '行业',
    city: '城市',
    dateTypeTitle: '日期',
    categoryId: 1,
    citySwitch: '',
    cityId: 0,
    category: '',
    mainActiveIndex: 0,
    activeId: null,
    cateMainActiveIndex: 0,
    cateActiveId: null,
    articleReqEvent: {
      categoryId: '',
      categoryType: 6,
      cityId: '',
      industryId: '',
      language: 1,
      title: '',
      userId: '',
      lately: '',
      page: 1,
      size: 20,
    },
    totalCount: 0,
    pageLoading: false,
    messagePath: '/pages/train/train',
    messageImg: '/images/logo新.png',
    getAdvertObj: {
      categoryType: 6,
      language: '',
      posterName: '',
      posterType: 4,
      showType: 1,
      trafficType: '',
    },
    bannerList: [],
    cateSelectList: [],
    citySelectList: [],
    industrySelectList: [],
    dateSelectList: [],
    dateList: [],
    dateActiveIndex: 0,
    dateTitle: '日期',
    dateSelectId: '',
    dateNavTitle: '',
  },
  // 监听搜索
  onSearch({ detail }) {
    this.setData({
      ['articleReqEvent.title']: detail,
    })
    this.getArticlePage(this.data.articleReqEvent)
  },
  // 日期筛选
  dateSelectHandle({ detail }) {
    let { dateSelectList } = this.data
    let index = dateSelectList.indexOf(detail)
    if (index > -1) {
      dateSelectList.splice(index, 1)
    } else {
      this.setData({
        'dateSelectList[0]': detail,
        dateTitle: this.data.dateList[detail].text,
        ['articleReqEvent.lately']: this.data.dateList[detail].text,
      })
    }
    if (dateSelectList.length == 0) {
      this.setData({
        dateTitle: this.data.lang['日期'],
        ['articleReqEvent.lately']: '',
      })
    }
    this.getArticlePage(this.data.articleReqEvent)
  },
  // 文章分类一级
  cateOnClickNav({ detail }) {
    this.setData({
      cateMainActiveIndex: detail.index || 0,
    })
  },
  // 文章分类二级
  cateOnClickItem({ detail }) {
    let categoryId = detail.id
    const { cateSelectList } = this.data
    const index = cateSelectList.indexOf(categoryId)
    if (index > -1) {
      cateSelectList.splice(index, 1)
    } else {
      cateSelectList.push(categoryId)
    }
    this.setData({
      cateSelectList,
      category: detail.text,
      ['articleReqEvent.categoryId']: cateSelectList.indexOf(0) != -1 ? 0 : JSON.stringify(cateSelectList).replace(/\[|]/g, ''),
    })
    this.getArticlePage(this.data.articleReqEvent)
    if (cateSelectList.length == 0) {
      this.setData({
        category: this.data.cateSeatTitle,
      })
    }
  },
  // 点击地区
  citySelectHandle({ detail }) {
    let { citySelectList } = this.data
    const index = citySelectList.indexOf(detail)
    if (index > -1) {
      citySelectList.splice(index, 1)
    } else {
      citySelectList.push(detail)
    }
    let list = []
    citySelectList.map((item) => {
      list.push(this.data.cityList[item].cityId)
    })
    this.setData({
      ['articleReqEvent.cityId']: list.indexOf(0) != -1 ? 0 : JSON.stringify(list).replace(/\[|]/g, ''),
      citySwitch: JSON.stringify(list).replace(/\[|]/g, ''),
      city: this.data.cityList[detail].text,
      citySelectList,
    })
    this.getArticlePage(this.data.articleReqEvent)
    if (citySelectList.length == 0) {
      this.setData({
        city: this.data.lang['地区'],
      })
    }
  },
  // 行业一级选择
  onClickNav({ detail }) {
    this.setData({
      mainActiveIndex: detail.index || 0,
    })
  },
  // 行业二级选择
  onClickItem({ detail }) {
    const { industrySelectList } = this.data
    const index = industrySelectList.indexOf(detail.id)
    if (index > -1) {
      industrySelectList.splice(index, 1)
    } else {
      industrySelectList.push(detail.id)
    }
    this.setData({
      industrySelectList,
      industry: detail.text,
      ['articleReqEvent.industryId']: industrySelectList.indexOf(0) != -1 ? 0 : JSON.stringify(industrySelectList).replace(/\[|]/g, ''),
    })
    this.getArticlePage(this.data.articleReqEvent)
    if (industrySelectList.length == 0) {
      this.setData({
        industry: this.data.lang['行业'],
      })
    }
  },
  // 删除搜索关键词
  onCancel() {
    this.setData({
      ['articleReqEvent.title']: '',
    })
    this.getArticlePage(this.data.articleReqEvent)
  },
  // 获取地区一二级列表
  async getAllIndustryList() {
    let { result } = await getAllIndustry(wx.getStorageSync('lang'))
    var res = [
      {
        id: 0,
        text: this.data.lang['全部行业'],
        children: [
          {
            id: 0,
            text: this.data.lang['全部'],
          },
        ],
      },
    ]
    this.setData({
      industryList: res.concat(result),
    })
  },
  // 获取城市列表
  async getCityList() {
    let { result } = await getCityList(wx.getStorageSync('lang'))
    var i = 1
    result.map((item) => {
      item.text = item.cityName
      item.cityId = item.cityId
      item.value = i
      i++
    })
    let arr = [{ text: this.data.lang['全大湾区'], value: 0, cityId: 0 }]
    result = arr.concat(result)
    this.setData({
      cityList: result,
    })
  },
  // 获取分类下拉菜单一二级列表
  async getCategoryList() {
    let { result } = await getCategoryList({
      type: 6,
      language: wx.getStorageSync('lang'),
    })
    let index = 0
    result.map(async (item) => {
      item.children = []
      item.text = item.categoryName
      let { result: res } = await getChildList(item)
      res.map((cItem) => {
        cItem.text = cItem.categoryName
        if (index == 0) {
          cItem.id = index++
        } else {
          cItem.id = cItem.categoryId
        }
        cItem.text = cItem.categoryName
        if (cItem.parentId == item.categoryId) {
          item.children.push(cItem)
        }
      })
      this.setData({
        categoryList: result,
        category: result[0].categoryName,
        cateSeatTitle: result[0].categoryName,
      })
    })
  },
  // 获取文章列表
  async getArticlePage(e) {
    this.getPosterList()
    this.setData({
      ['articleReqEvent.page']: 1,
    })
    let { result } = await getArticlePage(e)
    if (result.content.length != 0) {
      let afterChangeResult = result.content.map((item) => {
        if (item.publishTime != null) {
          item.publishTime = item.publishTime.split(' 00:00:00')[0]
        }
        return item
      })
      this.setData({
        totalCount: result.totalCount,
        momentList: afterChangeResult,
        showTips: false,
      })
    } else {
      this.setData({
        momentList: [],
        showTips: true,
      })
    }
  },
  // 滑动底部
  async scrollEnd() {
    if (this.data.momentList.length < this.data.totalCount) {
      this.setData({
        ['articleReqEvent.page']: this.data.articleReqEvent.page + 1,
      })
      let { result } = await getArticlePage(this.data.articleReqEvent)
      if (result.content.length != 0) {
        let afterChangeResult = result.content.map((item) => {
          if (item.publishTime != null) {
            item.publishTime = item.publishTime.split(' 00:00:00')[0]
          }
          return item
        })
        this.setData({
          totalCount: result.totalCount,
          momentList: this.data.momentList.concat(afterChangeResult),
        })
      }
    } else {
      wx.showToast({
        title: this.data.lang['没有更多数据了'],
      })
    }
  },
  // 获取广告
  async getPosterList() {
    this.setData({
      'getAdvertObj.language': wx.getStorageSync('lang'),
    })
    let { result } = await getPosterList(this.data.getAdvertObj)
    if (result) {
      result.map((item) => {
        item.bannerLink = `${app.globalData.host}/attach/showPic?attachId=${item.pic}`
      })
      this.setData({
        bannerList: result,
      })
    }
  },
  // 点击收藏
  async toCollectHandle({ detail }) {
    this.setData({
      ['articleReqEvent.articleId']: detail.momentId,
    })
    if (detail.collect == 1) {
      //取消收藏
      let { result } = await delCollect({ ids: detail.collectId })
      if (result) {
        this.getArticlePage(this.data.articleReqEvent)
      }
    } else {
      if (wx.getStorageSync('userId')) {
        let { result } = await saveCollect(this.data.articleReqEvent)
        if (result) {
          this.setData({
            collectStatus: result.status,
          })
          this.getArticlePage(this.data.articleReqEvent)
        }
      } else {
        wx.reLaunch({
          url: '/pages/index/index',
        })
      }
    }
  },
  // 点击列表进入文章详情
  toMomentDetailHandle({ detail }) {
    let vantObj = {
      type: detail.type,
      id: detail.momentId,
      title: detail.title,
      language: this.data.language,
    }
    this.vantDialog(vantObj)
  },
  // 点击广告进入客服
  adClickHandle({ detail }) {
    let vantObj = {
      type: detail.type,
      id: detail.posterId,
      title: detail.posterName,
      language: this.data.language,
    }
    this.vantDialog(vantObj)
  },
  //vant 弹窗组件（用于进入客服）
  vantDialog(e) {
    Dialog.confirm({
      title: this.data.lang['查看内容'],
      message: this.data.lang['跳转内容链接'],
      confirmButtonText: this.data.lang['确定'],
      cancelButtonText: this.data.lang['取消'],
      confirmButtonOpenType: 'contact',
      sendMessageTitle: e.title,
      sendMessagePath: `${this.data.messagePath}?${e.id},${e.type}`,
      sendMessageImg: this.data.messageImg,
      showMessageCard: true,
    })
      .then(async () => {
        setTimeout(() => {
          console.log('没啥没啥')
        })
      })
      .catch((err) => err)
  },
  // 点击转发
  toForwardHandle({ detail }) {
    wx.setClipboardData({
      data: detail,
      success: () => {
        wx.showToast({
          title: this.data.lang['已复制网站网址'],
          icon: 'none',
        })
      },
    })
  },
  // 获取本地用户信息
  initLocaStayInfo() {
    let userId = wx.getStorageSync('userId')
    if (userId) {
      this.setData({
        ['articleReqEvent.userId']: userId,
      })
    }
  },
  // 初始化日期
  initDate() {
    let monthIndex = 12
    let year = new Date().getFullYear()
    let month = new Date().getMonth()
    let list = []
    for (let i = 0; i < monthIndex; i++) {
      month += 1
      if (month > 12) {
        month = 1
        year += 1
      }
      list.push(year + '-' + month.toString().padStart(2, '0'))
    }
    this.setData({
      dateList: list.map((item, index) => {
        return {
          id: index,
          value: index,
          text: item,
        }
      }),
    })
  },
  // 匹配拼装字符串
  matchingStr() {
    let dateTitle = ''
    let { dateSelectId, dateActiveIndex, dateList } = this.data
    dateList.map((item) => {
      if (item.id == dateActiveIndex) {
        dateTitle = item.value
      }
      item.children.map((cItem) => {
        if (cItem.id == dateSelectId) {
          dateTitle = dateTitle + '-' + cItem.value.toString().padStart(2, '0')
        }
      })
    })
    this.setData({
      dateTitle,
      'articleReqEvent.lately': dateTitle,
    })
    this.getArticlePage(this.data.articleReqEvent)
  },
  onShow() {
    this.initLocaStayInfo()
  },
  // 初始化
  onLoad() {
    let lang = wx.getStorageSync('lang')
    if (lang == 2) {
      this.setData({
        dateList: this.data.twDateList,
      })
    }
    if (lang == 3) {
      this.setData({
        dateList: this.data.enDateList,
      })
    }
    const langData = _t()
    this.setData({
      ['articleReqEvent.language']: lang,
      industry: langData['行业'],
      city: langData['地区'],
      dateTitle: langData['日期'],
      lang: langData,
    })
    wx.setNavigationBarTitle({
      title: langData['活动及培训'],
    })
    this.initDate()
    this.getPosterList()
    this.initLocaStayInfo()
    this.getCategoryList()
    this.getAllIndustryList()
    this.getCityList()
    this.getArticlePage(this.data.articleReqEvent)
  },
})
